const fs = require('fs')
const path = require('path')
const send = require('koa-send')
const { resolve } = require('path')
const uploadPath = path.join(__dirname, '../upload')


function getFile (reader, upStream) {
  return new Promise(function (result) {
    let stream = reader.pipe(upStream); // 可读流通过管道写入可写流
    stream.on('finish', function (err) {
      result(err);
    });
  });
}

// api/file/upload
exports.upload = async function(ctx) {
  let metadataFile = ctx.request.files['video']; // 获取上传文件
  let filePath = `${uploadPath}/${metadataFile['name']}`;

  // axios的onUploadProgress方法是纯前端判断上传进度？
  const progress = function(event) {  
    let percent = Math.floor((100 / metadataFile.size) * event.loaded);  
    console.log(`上传进度: ${percent}%`);  
    // 这里可以将进度信息发送给前端，如 ctx.body = percent;  
    // ctx.body = percent;
  }; 
  // 创建可读流
  const reader = fs.createReadStream(metadataFile.path)
  reader.on('data', function(chunk) {
    progress({ loaded: chunk.length })
  })  
  // 创建可写流
  const upStream = fs.createWriteStream(filePath);
  // 可读流通过管道写入可写流
  reader.pipe(upStream);


  ///////////////////////////
 /*  const progress = (event) => {  
    let percent = Math.floor((100 / ctx.file.size) * event.loaded);  
    console.log(`上传进度: ${percent}%`);  
    // 这里可以将进度信息发送给前端，如 ctx.body = percent;  
  };  
  fs.createReadStream(path.join(__dirname, 'uploads', ctx.file.originalname))  
    .on('data', (chunk) => progress({ loaded: chunk.length }))  
    .pipe(fs.createWriteStream(path.join(__dirname, 'uploads', 'resized_' + ctx.file.originalname)));  
  // 上传成功后返回响应  
  ctx.body = '文件上传成功！';   */
  ///////////////////////////

  const isError = await getFile(reader, upStream); //等待数据存储完成
  
  if (isError) {
    return ctx.body = {
      message: "文件上传失败"
    }
  }

  return ctx.body = {
      success: true,
      message: "文件上传成功",
  }   
}
  